package com.solotiger.douban.ui;

import android.Manifest;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.util.SparseArray;
import android.view.MenuItem;

import com.solotiger.douban.R;
import com.solotiger.douban.ui.base.BaseBarFragment;
import com.solotiger.douban.ui.base.BaseFragment;
import com.solotiger.douban.ui.base.BaseFragmentActivity;
import com.solotiger.douban.ui.fragment.main.BookFragment;
import com.solotiger.douban.ui.fragment.main.MovieFragment;
import com.solotiger.douban.ui.fragment.main.MusicFragment;
import com.solotiger.douban.util.FileUtil;
import com.solotiger.douban.util.RxHelper;
import com.tbruyelle.rxpermissions2.RxPermissions;

import butterknife.BindView;
import io.reactivex.functions.Consumer;


public class MainActivity extends BaseFragmentActivity
        implements NavigationView.OnNavigationItemSelectedListener {


    @BindView(R.id.drawer_layout)
    DrawerLayout drawer;

    public enum FragmentEnum {
        MOVIE(R.id.navigation_movie, MovieFragment.class),
        MUSIC(R.id.navigation_music, MusicFragment.class),
        BOOK(R.id.navigation_book, BookFragment.class);

        //外层LayoutId
        public final int tabId;
        // 对应Fragment的class
        public final Class<? extends BaseBarFragment> fragmentClass;

        private FragmentEnum(int tabId,
                             Class<? extends BaseBarFragment> fragmentClass) {
            this.tabId = tabId;
            this.fragmentClass = fragmentClass;
        }

        // 默认打开的Fragment
        public final static FragmentEnum DEFAULT = MOVIE;
    }

    private final SparseArray<BaseBarFragment> fragmentArray = new SparseArray<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setTitle("");

        //申请权限
        new RxPermissions(mContext)
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .compose(RxHelper.bind(this))
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            FileUtil.fileInit();
                        } else {
                            showMessage("您禁用了访问SD的权限!");
                        }
                    }
                });

        init();

        setTabSelection(FragmentEnum.DEFAULT);
    }

    private void init() {
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, getToolbar(), R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        initBottom();
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_main;
    }

    @Override
    public void onBackPressed() {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }


    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            // Handle the camera action
        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.navigation_movie:
                    setTabSelection(FragmentEnum.MOVIE);
                    return true;
                case R.id.navigation_music:
                    setTabSelection(FragmentEnum.MUSIC);
                    return true;
                case R.id.navigation_book:
                    setTabSelection(FragmentEnum.BOOK);
                    return true;
            }
            return false;
        }
    };

    public void setTabSelection(FragmentEnum fragmentEnum) {
        if (fragmentEnum == null) {
            fragmentEnum = FragmentEnum.DEFAULT;
        }

        // 当前Fragment已经是选中状态则直接返回
        BaseBarFragment fragment = fragmentArray.get(fragmentEnum.tabId);
        if (fragment != null && fragment.isFront()) {
            return;
        }

        if (fragmentEnum == FragmentEnum.MUSIC) {
            setTitle(getString(R.string.title_music));
        } else if (fragmentEnum == FragmentEnum.BOOK) {
            setTitle(getString(R.string.title_book));
        } else if (fragmentEnum == FragmentEnum.MOVIE) {
            setTitle(getString(R.string.title_movie));
        }

        // 隐藏其他Fragment
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        for (int i = 0, len = fragmentArray.size(); i < len; i++) {
            BaseFragment f = fragmentArray.valueAt(i);
            transaction.hide(f);
        }
        if (fragment == null) {
            // 新建Fragment
            try {
                fragment = fragmentEnum.fragmentClass.newInstance();
                fragmentArray.put(fragmentEnum.tabId, fragment);
                transaction.add(R.id.tab_content, fragment);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            // 显示已有的Fragment
            transaction.show(fragment);
        }
        transaction.commitAllowingStateLoss();
    }

    private void initBottom() {
        BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
    }
}
